<template>
  <div class="user">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-page-header
          @back="$router.back()"
          :content="courseName || '上传视频'"
        >
        </el-page-header>
      </div>
      <dh-form
        label-width="100px"
        label-position="left"
        :formConfig="formConfig"
        :formParams="formParams"
        ref="dhForm"
      >
        <template v-slot:video="{ item }">
          <el-form-item

            style="width: 100%"
            v-bind="item"

            :prop="item.name"
          >
          <input ref="videoFile" type="file"/>
          <!-- <el-button @click="$refs.videoFile.click()" size="small" type="primary">点击上传</el-button> -->
          </el-form-item>
        </template>
        <template v-slot:image="{ item }">
          <el-form-item
            :prop="item.name"
            style="width: 100%"
            v-bind="item"
          >
          <input  ref="imgFile" type="file"/>
          <!-- <el-button @click="$refs.imgFile.click()" size="small" type="primary">点击上传</el-button> -->
          </el-form-item>
        </template>
      </dh-form>
      <el-button
        @click="saveCourse"
        type="primary"
        :loading="submitLoading !== 0"
        style="margin: 10px auto; display: block"
        >{{
          submitLoading === 0 ? '保存':  submitLoading === 1 ? "上传中..." : "转码中..."
        }}</el-button
      >
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import DhForm from '@/components/dh-components/dh-form/index.vue'
// import CourseImg from './courseImg.vue'
import {
  aliyunImagUploadAddressAdnAuth, aliyunVideoUploadAddressAdnAuth,
  aliyunTransCode, aliyunTransCodePercent
} from '@/services/aliyun-upload'
import {
  getCourseById
} from '@/services/course'
export default Vue.extend({
  components: {
    DhForm
    // CourseImg
  },
  name: 'coursesVideo',
  data () {
    return {
      courseName: '',
      formParams: {

      },
      formConfig: [
        {
          name: 'courseName',
          label: '课程',
          disabled: true
        },
        {
          name: 'lessonName',
          label: '课时',
          disabled: true
        },
        {
          name: 'video',
          label: '视频上传',
          htmlType: 'slot'
        },
        {
          name: 'image',
          label: '封面上传',
          htmlType: 'slot'
        }
      ],
      uploader: '',
      imageURL: '',
      videoId: '',
      submitLoading: 0

    }
  },
  computed: {
    video () {
      // return (this.$refs.videoFile as any).$parent
      return (this.$refs as any).videoFile
    },
    image () {
      // return (this.$refs.imgFile as any).$parent
      return (this.$refs as any).imgFile
    }
  },
  created () {
    this.inituploader()
    this.queryId()
  },
  methods: {
    async queryId () {
      const { data } = await getCourseById({ courseId: this.$route.params.id })
      this.formParams = data
    },
    inituploader () {
      this.uploader = new window.AliyunUpload.Vod({
      // 阿里账号ID，必须有值 ，值的来源https://help.aliyun.com/knowledge_detail/37196.html
        userId: '1618139964448548',
        // 上传到点播的地域， 默认值为'cn-shanghai',//eu-central-1,ap-southeast-1
        region: '',
        // 分片大小默认1M，不能小于100K
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo: any) => {
          this.submitLoading = 1
          let uploadAddressAuth: any
          if (uploadInfo && uploadInfo.isImage) {
            const { data } = await aliyunImagUploadAddressAdnAuth()
            this.imageURL = data.imageURL
            uploadAddressAuth = data
            console.log(data)
          } else {
            try {
              const { data } = await aliyunVideoUploadAddressAdnAuth({
                fileName: uploadInfo.file.name,
                imageUrl: this.imageURL
              })
              uploadAddressAuth = data
              this.videoId = data.videoId
            } catch (error) {
              console.log(error)
            }
          }
          (this.uploader as any).setUploadAuthAndAddress(uploadInfo, uploadAddressAuth.uploadAuth, uploadAddressAuth.uploadAddress, uploadAddressAuth.imageId || uploadAddressAuth.videoId)
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          console.log('chenggong', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo: any, code: any, message: any) {
          console.log(uploadInfo)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: function (uploadInfo: any, totalSize: any, loadedPercent: any) {
          console.log(uploadInfo, totalSize, loadedPercent)
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo: any) {
          console.log(uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo: any) => {
          this.submitLoading = 2
          const { data } = await aliyunTransCode({
            lessonId: (this.$route as any).query.lessonId,
            fileId: this.videoId,
            fileName: (this.video as any).files[0].name,
            coverImageUrl: this.imageURL
          })
          const timer = setInterval(async () => {
            const { data } = await aliyunTransCodePercent({
              lessonId: (this.$route as any).query.lessonId
            })
            if (data === 100) {
              window.clearInterval(timer)
              this.$message.success('转码成功')
              this.submitLoading = 0
            }
            console.log(data)
          }, 3000)

          console.log(data)
        }
      })
    },
    saveCourse () {
      // const videoFile = (this.video as any).fileList[0]
      // const imgFile = (this.image as any).fileList[0]
      const videoFile = (this.video as any).files[0]
      const imgFile = (this.image as any).files[0]
      const userData = '{"Vod":{}}'
      const uploader: any = this.uploader
      imgFile && uploader.addFile(imgFile, null, null, null, userData)
      videoFile && uploader.addFile(videoFile, null, null, null, userData)
      // 开始上传
      uploader.startUpload()
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
